package com.nativetalk.service.member.retrieve;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMemberRegisterSms;
import com.nativetalk.bean.member.TdNtMemberRetrieve;
import com.nativetalk.bean.member.TdNtMemberRetrievePsd;
import com.nativetalk.bean.send.TwNtSendHisInsert;
import com.nativetalk.bean.sms.Sms;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.*;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TwNtSendHisDao;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 15/12/24.
 */
@Service
public class MemberRetrieveServiceImpl implements MemberRetrieveService {
    private static Logger logger = Logger.getLogger(MemberRetrieveServiceImpl.class);
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TwNtSendHisDao twNtSendHisDao;

    @Override
    @Transactional
    public RetInfo retrieveSms(Sms sms) {
        String logInfo = this.getClass().getName() + ":retrieveSms:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            TdNtMemberRegisterSms tdNtMemberRegisterSms = tdNtMemberDao.findTdNtMemberRegisterSms(sms.getMemb_phone());
            if (tdNtMemberRegisterSms == null) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("MEMBER.RETRIEVE.ERROR"));
            } else {
                Map<String, Integer> map = new HashMap<>();
                String key = "day" + sms.getMemb_phone();
                String register = "retrieve" + sms.getMemb_phone();
                String sencod = "sencod" + sms.getMemb_phone();
                if (MemcachedUtils.get(key) != null) {
                    map = (Map<String, Integer>) MemcachedUtils.get(key);
                    int size = map.get("size") + 1;
                    logger.info("1天内短信发送次数{phone:" + sms.getMemb_phone() + ",size:" + size + "}");
                    if (size >= 20) {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                    } else {
                        //判断60秒内是否发送过短信
                        if (!("0".equals(MemcachedUtils.get(sencod)))) {
                            String content = "您的验证码为CODE";
                            String code = SmsCodeUtil.getSmsCode();
                            content = content.replace("CODE", code);
                            //验证码过期为5分钟
                            logger.info("短信验证码为:" + code);
                            if (MemcachedUtils.get(register) == null) {
                                MemcachedUtils.add(register, code, 5 * 60);
                            } else {
                                MemcachedUtils.replace(register, code, 5 * 60);
                            }
                            TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
                            twNtSendHis.setPhoneno(sms.getMemb_phone());
                            twNtSendHis.setYyyymmdd(CommonUtil.getMonth(now));
                            twNtSendHis.setSms_provider_id(Integer.parseInt(code));
                            boolean flag = SMSUtil.sendSms(sms, content);
                            if (flag) {
                                twNtSendHis.setSms_type("Y");
                                MemcachedUtils.add(sencod, "0", 60);
                                map.put("size", size);
                                MemcachedUtils.add(key, map, 24 * 60 * 60);
                                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                                retInfo.setTip(ValidationMessages.getValue("MESSAGE.YES"));
                            } else {
                                twNtSendHis.setSms_type("N");
                                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                                retInfo.setTip(ValidationMessages.getValue("MESSAGE.NO"));
                            }
                            twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                        } else {
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                        }
                    }
                } else {
                    logger.info("1天内短信发送次数{phone:" + sms.getMemb_phone() + ",size:" + 1 + "}");
                    //判断60秒内是否发送过短信
                    if (!("0".equals(MemcachedUtils.get(sencod)))) {
                        //TsGvDict tsGvDict = Memcached.tsGvdictMap.get("1");
                        //String content = tsGvDict.getCode_name();
                        String content = "您正在找回密码,验证码：CODE（5分钟内有效，如非本人操作请忽略）\"";
                        String code = "" + (int) (Math.random() * 1000000);
                        content = content.replace("CODE", code);
                        //验证码过期为5分钟
                        logger.info("短信验证码为:" + code);
                        MemcachedUtils.add(register, code, 5 * 60);
                        TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
                        twNtSendHis.setPhoneno(sms.getMemb_phone());
                        twNtSendHis.setYyyymmdd(CommonUtil.getMonth(now));
                        twNtSendHis.setSms_provider_id(Integer.parseInt(code));
                        boolean flag = SMSUtil.sendSms(sms, content);
                        if (flag) {
                            twNtSendHis.setSms_type("Y");
                            MemcachedUtils.add(sencod, "0", 60);
                            map.put("size", 1);
                            MemcachedUtils.add(key, map, 24 * 60 * 60);
                            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                            retInfo.setTip(ValidationMessages.getValue("MESSAGE.YES"));
                        } else {
                            twNtSendHis.setSms_type("N");
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip(ValidationMessages.getValue("MESSAGE.NO"));
                        }
                        twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                    }
                }
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo retrieveByCodeSms(Sms sms) {
        String logInfo = this.getClass().getName() + ":retrieveSms:";
        logger.info("======" + logInfo + "begin======");
        Date now = new Date();
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Integer> map = new HashMap<>();
            String key = "day" + sms.getMemb_phone();
            String register = "registerAndLogin" + sms.getMemb_phone();
            String sencod = "sencod" + sms.getMemb_phone();
            if (MemcachedUtils.get(key) != null) {
                map = (Map<String, Integer>) MemcachedUtils.get(key);
                int size = map.get("size") + 1;
                logger.info("1天内短信发送次数{phone:" + sms.getMemb_phone() + ",size:" + size + "}");
                if (size >= 20) {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                } else {
                    //判断60秒内是否发送过短信
                    if (!("0".equals(MemcachedUtils.get(sencod)))) {
                        String content = "您的验证码为CODE";
                        String code = SmsCodeUtil.getSmsCode();
                        content = content.replace("CODE", code);
                        //验证码过期为5分钟
                        logger.info("短信验证码为:" + code);
                        if (MemcachedUtils.get(register) == null) {
                            MemcachedUtils.add(register, code, 5 * 60);
                        } else {
                            MemcachedUtils.replace(register, code, 5 * 60);
                        }
                        TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
                        twNtSendHis.setPhoneno(sms.getMemb_phone());
                        twNtSendHis.setYyyymmdd(CommonUtil.getMonth(now));
                        twNtSendHis.setSms_provider_id(Integer.parseInt(code));
                        boolean flag = SMSUtil.sendSms(sms, content);
                        if (flag) {
                            twNtSendHis.setSms_type("Y");
                            MemcachedUtils.add(sencod, "0", 60);
                            map.put("size", size);
                            MemcachedUtils.add(key, map, 24 * 60 * 60);
                            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                            retInfo.setTip(ValidationMessages.getValue("MESSAGE.YES"));
                        } else {
                            twNtSendHis.setSms_type("N");
                            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                            retInfo.setTip(ValidationMessages.getValue("MESSAGE.NO"));
                        }
                        twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                    } else {
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                    }
                }
            } else {
                logger.info("1天内短信发送次数{phone:" + sms.getMemb_phone() + ",size:" + 1 + "}");
                //判断60秒内是否发送过短信
                if (!("0".equals(MemcachedUtils.get(sencod)))) {
                    //TsGvDict tsGvDict = Memcached.tsGvdictMap.get("1");
                    //String content = tsGvDict.getCode_name();
                    String content = "您正在使用验证码登录,验证码：CODE（5分钟内有效，如非本人操作请忽略）\"";
                    String code = SmsCodeUtil.getSmsCode();
                    content = content.replace("CODE", code);
                    //验证码过期为5分钟
                    logger.info("短信验证码为:" + code);
                    MemcachedUtils.add(register, code, 5 * 60);
                    TwNtSendHisInsert twNtSendHis = new TwNtSendHisInsert();
                    twNtSendHis.setPhoneno(sms.getMemb_phone());
                    twNtSendHis.setYyyymmdd(CommonUtil.getMonth(now));
                    twNtSendHis.setSms_provider_id(Integer.parseInt(code));
                    boolean flag = SMSUtil.sendSms(sms, content);
                    if (flag) {
                        twNtSendHis.setSms_type("Y");
                        MemcachedUtils.add(sencod, "0", 60);
                        map.put("size", 1);
                        MemcachedUtils.add(key, map, 24 * 60 * 60);
                        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                        retInfo.setTip(ValidationMessages.getValue("MESSAGE.YES"));
                    } else {
                        twNtSendHis.setSms_type("N");
                        retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                        retInfo.setTip(ValidationMessages.getValue("MESSAGE.NO"));
                    }
                    twNtSendHisDao.insertTwNtSendHis(twNtSendHis);
                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MESSAGE.REPAT"));
                }
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    @Transactional
    public RetInfo retrieve(TdNtMemberRetrieve tdNtMemberRetrieve) {
        String logInfo = this.getClass().getName() + ":retrieve:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            /**
             * 判断验证码是否正确
             */
            if (MemcachedUtils.get("retrieve" + tdNtMemberRetrieve.getMemb_phone()) == null
                    || !MemcachedUtils.get("retrieve" + tdNtMemberRetrieve.getMemb_phone()).equals(tdNtMemberRetrieve.getCode())) {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("REGISTER.CODE.ERROR"));
            } else {
                /**
                 * 判断用户是否已注册
                 */
                TdNtMemberRetrievePsd tdNtMemberRetrievePsd = tdNtMemberDao.findTdNtMemberRetrievePsd(tdNtMemberRetrieve.getMemb_phone());
                if (tdNtMemberRetrievePsd != null) {
                    /**
                     * 删除原缓存
                     */
                    MemcachedUtils.delete(tdNtMemberRetrievePsd.getToken());
                    /**
                     * 更新用户密码及token
                     */
                    tdNtMemberRetrievePsd.setMemb_password(MD5.code(tdNtMemberRetrieve.getMemb_password()));
                    tdNtMemberRetrievePsd.setToken(CommonUtil.getToken());
                    tdNtMemberDao.updateTdNtMemberRetrievePsd(tdNtMemberRetrievePsd);

                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip(ValidationMessages.getValue("MEMBER.RETRIEVE.ERROR"));

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("MEMBER.RETRIEVE.SUCCESS"));
                }
            }
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
